<template>
  <BoTable ref="tableRef" :request="_fetchList" :columns="columns">
    <template #leftContainer>
      <div class="mr-4 w-48 border-r border-[rgba(255,255,255,.3)]">
        <div class="mr-2 flex h-10 items-center justify-between">
          <h3 class="module-title mb-0 mr-7">监测列表</h3>
        </div>
        <Tree
          :tree-data="treeData"
          :selected-keys="[selectKeys]"
          :expanded-keys="expandedKeys"
          :field-names="{ key: 'id', title: 'structureName' }"
        >
          <template #title="scope">
            <span @click="() => handleSelectStructure(scope)">{{
              scope.structureName
            }}</span>
          </template>
        </Tree>
      </div>
    </template>
  </BoTable>
  <Modal
    v-model:open="visible"
    :title="false"
    destroyOnClose
    wrap-class-name="view_modal"
    width="100%"
    :footer="false"
  >
    <triggerData
      :options="options"
      title="实时波形数据"
      show-witch="realTime"
      :deviceInfo="[code]"
    >
      <template #header></template>
    </triggerData>
  </Modal>
</template>

<route lang="json">
{
  "meta": {
    "title": "实时数据"
  }
}
</route>

<script setup lang="tsx">
import { computed, onMounted, ref, useTemplateRef } from 'vue';
import { deviceEnum } from '@/constants/index';
import { useDicts } from '@boeyo/portal';
import { listToEnum, treeToArray } from '@boeyo/shared';
import { BoTable, BoTableProps } from '@boeyo/ui';
import { Modal, Tree } from 'ant-design-vue';
import triggerData from '@/components/triggerData/index.vue';
import {
  fetchList,
  fetchStructureTree,
  getDeviceManufacturerSelect,
  getDeviceModelSelect,
  getDeviceProjectSelect,
} from './api';

const visible = ref(false);
const code = ref('');

const { deviceTypeEnum } = useDicts(['device_type']);

// 获取表单下拉框数据
const manufacturerEnum = ref<Record<string, any>>({});
const projectEnum = ref<Record<string, any>>({});
const modelEnum = ref<Record<string, any>>({});

const init = () => {
  getDeviceManufacturerSelect({ type: deviceEnum.TERMINAL }).then(
    ({ data }) => {
      manufacturerEnum.value = listToEnum(data, 'name', 'facId');
    },
  );
  getDeviceProjectSelect().then(({ data }) => {
    projectEnum.value = listToEnum(data, 'name', 'projectId');
  });
  getDeviceModelSelect().then(({ data }) => {
    modelEnum.value = listToEnum(data, 'model', 'modelId');
  });
};
init();

const tableRef = useTemplateRef('tableRef');
const columns = computed<BoTableProps['columns']>(() => {
  return [
    {
      title: '台站',
      dataIndex: 'stationId',
    },
    {
      title: '硬件序列号',
      dataIndex: 'deviceCode',
    },
    {
      title: '软件版本',
      dataIndex: 'version',
      hideInSearch: true,
    },
    {
      title: '设备类型',
      dataIndex: 'deviceType',
      valueType: 'select',
      valueEnum: deviceTypeEnum.value,
    },
    {
      title: '设备型号',
      dataIndex: 'model',
    },
    {
      title: '设备厂商',
      dataIndex: 'manufacturer',
      hideInSearch: true,
    },
    {
      title: '经度',
      dataIndex: 'longitude',
      hideInSearch: true,
    },
    {
      title: '纬度',
      dataIndex: 'latitude',
      hideInSearch: true,
    },
    {
      title: '高程',
      dataIndex: 'height',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: '_actions',
      fixed: 'right',
      hideInSearch: true,
      actions() {
        return [
          {
            text: '实时波形数据',
            onClick(record) {
              code.value = `${record.networkCode}.${record.stationCode}`;
              visible.value = true;
            },
          },
        ];
      },
    },
  ];
});

const treeData = ref();
const expandedKeys = ref([]);
onMounted(async () => {
  const result = await fetchStructureTree();
  treeData.value = result.data;
  expandedKeys.value = treeToArray(treeData.value).map((item) => item.id);
});

const _fetchList = async (_params) => {
  const res: any = await fetchList({ ...params, ..._params });
  res.rows = res.rows.map((item: any) => {
    item.latitude = (+item.latitude || 0).toFixed(4);
    item.longitude = (+item.longitude || 0).toFixed(4);
    return item;
  });
  return {
    rows: res.rows,
    total: res.total,
  };
};

const selectKeys = ref(undefined);
let params: Record<string, any> = {};

const handleSelectStructure = (scope) => {
  const { monitoringType, id } = scope;
  params = {};
  if (id === selectKeys.value) {
    selectKeys.value = undefined;
  } else {
    selectKeys.value = id;
    switch (monitoringType) {
      case '1':
        params.netId = id;
        break;
      case '2':
        params.regionId = id;
        break;
      case '3':
        params.structureId = id;
        break;
    }
  }

  tableRef.value.refresh();
};
const options = computed(() => {
  return {
    presentationList: [
      {
        label: '原始数据',
        value: 'value',
        disabled: false,
      },
      {
        label: '高通滤波',
        value: 'hpFilter',
        disabled: false,
      },
    ],
    dataTypeList: [
      {
        label: '加速度',
        value: 'accelerationData',
        disabled: false,
      },
    ],
    channelList: [
      {
        value: 'EIZ',
        label: 'EIZ-竖桥向',
        color: '#F16995',
      },
      {
        value: 'EIN',
        label: 'EIN-横桥向',
        color: '#77E3F9',
      },
      {
        value: 'EIE',
        label: 'EIE-纵桥向',
        color: '#DFC428',
      },
    ],
    deviceInfoList: [
      {
        label: code.value,
        value: code.value,
        disabled: true,
      },
    ],
  };
});
</script>
